﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using AndreySmirnov.BLToolkitUtils.VSPackage.Model.Config;

namespace AndreySmirnov.BLToolkitUtils.VSPackage.Model.ViewModel
{
	public class UIViewModel : ViewModelBase
	{
		public ConnectionViewModel Connection { get; protected set; }
		public CodeGenerationSettingsViewModel GlobalSettings { get; protected set; }


	    private bool m_useCommonSettingsForAllTables;

	    public bool UseCommonSettingsForAllTables
	    {
	        get { return m_useCommonSettingsForAllTables; }
	        set
	        {
	            m_useCommonSettingsForAllTables = value;
                NotifyPropertyChange("UseCommonSettingsForAllTables");
                NotifyPropertyChange("TablesSettings");
	        }
	    }

	    private ObservableCollection<CodeGenerationSettingsViewModel> m_tablesSettings;
	    public ObservableCollection<CodeGenerationSettingsViewModel> TablesSettings
	    {
	        get
	        {
                return m_useCommonSettingsForAllTables 
                    ? new ObservableCollection<CodeGenerationSettingsViewModel>()
                    : m_tablesSettings;
	        }
	        set
	        {
                m_tablesSettings = value;
                NotifyPropertyChange("TablesSettings");
	        }
	    }

	    public bool IsDirty { get; set; }
		public event Action Modified;

		public void InvokeModified()
		{
			Action handler = Modified;
			if (handler != null)
			{
				handler();
			}
		}

		public void Init(BLTConfig config)
		{
			Connection = new ConnectionViewModel
			             	{
			             		ConnectionInfo = config.ConnectionInfo,
			             	};
		    GlobalSettings = new CodeGenerationSettingsViewModel
		                         {
		                             Settings = config.GenerationTask.GlobalSettings ?? new BLTCodeGenerationSettings(),
		                         };
		    UseCommonSettingsForAllTables = true;
			Connection.PropertyChanged += OnPropertyChanged;
            GlobalSettings.PropertyChanged += OnPropertyChanged;
			IsDirty = false;
		}

		private void OnPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
		{
			if (IsDirty)
				return;
			IsDirty = true;
			InvokeModified();
		}

		public void UpdateData(BLTConfig config)
		{
			config.ConnectionInfo = Connection.ConnectionInfo;
		    config.GenerationTask.GlobalSettings = GlobalSettings.Settings;
		}
	}
}
